package com.student.realm;

import com.student.bean.User;
import com.student.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.Objects;

public class MyPerRealm extends AuthorizingRealm {
    @Resource
    private UserMapper userMapper;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    public String getName() {
        return "MyPerRealm";
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //授权信息对象，用来保存所有角色和授权信息
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer userId = user.getUserid();
        //获取用户角色ID
        Integer roleId = userMapper.selectRoleId(userId);
        //根据角色ID获取角色名
        String roleName = userMapper.selectRole(roleId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(roleName);

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());

        User user = userMapper.selectUserByLogname(username);
        if (user == null) {
            throw new UnknownAccountException("账号异常/不存在");
        }
        //获取token中的密码并比较是否与数据库中一致
        String salt =user.getSalt();
        //加盐
        String saltPassword = new Md5Hash(password,salt).toString();
        String passwordInDatabase = user.getLoginpassword();
        //比较加盐后结果
        boolean b = Objects.equals(saltPassword, passwordInDatabase);
        if (!b) {
            throw new IncorrectCredentialsException("密码错误");
        }

        return new SimpleAuthenticationInfo(user, password, getName());
    }
}
